<?php
	function validateRequiredFields($editpageflag){
		$errorList = array();
		$currentSubgoalName = "no name";
		foreach($_POST as $key=>$value) {
			if(startsWith($key, "subgoalname")){					
				if (($value == "")? $currentSubgoalName = "no name": $currentSubgoalName = $value);
				}
			if ($value == "" && $key != "description" && $key != "deadline"
					&& startsWith($key, "subgoaldeadline") == false){						
						
				$temp = $key;
				if ($temp != str_replace("_","",$temp)){
					# subgoal
					$splittedId = preg_split("[_]", $temp);
					if($editpageflag == true){
						$errorList[] = "Please fill out required field '$splittedId[0]' of subgoal '".$currentSubgoalName."'";
					}else{
						$errorList[] = "Please fill out required field '$splittedId[0]' of subgoal #".intval($splittedId[1]+1);
					}					
				}else{
					#goal
					$errorList[] = "Please fill out required goal field '$key'.";
				}
			}
		}
		return $errorList;	
	}
	
	function validateExistingGoalName($goalname, $userid){
		mysql_connect("localhost", "web964","pass17") or die ("Connection failed.");
		mysql_select_db("usr_web964_1") or die ("Database does not exist.");	
		$result = mysql_query("SELECT name FROM goal WHERE name='$goalname' AND fk_userid='$userid'" ) or die ("MySQL-Error: " . mysql_error());
		if (mysql_num_rows($result) > 0){
			return "Goalname '$goalname' already exists.";
		}		
	}
	
	function validateExistingGoalNameOnEditPage($goalid, $goalname){
		mysql_connect("localhost", "web964","pass17") or die ("Connection failed.");
		mysql_select_db("usr_web964_1") or die ("Database does not exist.");	
		$result = mysql_query("SELECT name FROM goal WHERE name='$goalname' AND NOT id='$goalid'" ) or die ("MySQL-Error: " . mysql_error());
		if(mysql_num_rows($result) > 0){
			return "Goalname '$goalname' already exists.";
		}		
	}
		
	
	function validateEqualSubgoalNames(){
		$equalsSubgoalNamesExist = "";
		$arrayWithNames = array();
		foreach($_POST as $key=>$value) {
			if (startsWith($key, "subgoalname")){
				$arrayWithNames[] = $value;
			}
		}
		foreach(array_count_values($arrayWithNames) as $key=>$value) {
			if ($value != 1){
				return $equalsSubgoalNamesExist = "You have at least two subgoals with equal names.";
			}			
		}		
		return $equalsSubgoalNamesExist;
	}
	

	
	function validateDeadlines(){
		$errorMessages = array();
		foreach($_POST as $key=>$value) {
			if ((startsWith($key, "subgoaldeadline") OR $key == "deadline") AND $value != ""){
				// Date yy-m-d or yyyy-mm-dd
				//00-1-1 through 99-12-31 and 1900-01-01 through 2099-12-31
				//Matches invalid dates such as February 31st
				$date =  preg_split("/[-]/", $value);
				if(count($date) == 3){
					$year =  $date['0'];
					$month =  $date['1'];
					$day = $date['2'];
				}else{
					$year =  "";
					$month =  "";
					$day = "";
				}
					
				if(preg_match('/\b(19|20)?[0-9]{2}[-](0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])\b/', $value) == false){
					$errorMessages[] = "Date format of deadline '".$value. "' is wrong.";
				}else if (!checkdate ( $month , $day , $year )){
					$errorMessages[] = "Date  '".$value. "' is not a correct date.";
				}
			}
		}
		# check whether all subgoal are in the future
		if(date_default_timezone_set('Europe/Berlin') && count($errorMessages) == 0){
			foreach($_POST as $key=>$value) {
				if ((startsWith($key, "subgoaldeadline") OR $key == "deadline") AND $value != ""){
					if ( strtotime($value) -  strtotime(date("Y-m-d")) < 0){
						$errorMessages[] = "The date ".$value. " is in the past.";
					}
				}
			}
		}
		
		# check whether subgoals deadlines are earlier as goaldeadline
		if (count($errorMessages) == 0 && $_POST['deadline'] !== ""){
					
			foreach($_POST as $key=>$value) {
				if ((startsWith($key, "subgoaldeadline")) AND $value != ""){
					if (strtotime($value) > strtotime($_POST['deadline'])){
						$errorMessages[] = "The date ".$value. " should be earlier than goal deadline ".$_POST['deadline'].".";
					}
				}
			}
			
		}
		
		return $errorMessages;
	}
	
	function validateGoalValues($measuretype, $startValue, $currentValue, $targetValue){
		$errorMessages = array();
		
		#echo $startValue." ".$currentValue." ".$targetValue;
		
		switch ($measuretype) {
			case '1': #integer
				if (!is_integer2($startValue)){
					$errorMessages[] = "Start value of goal is invalid."; 
				}
				if (!is_integer2($currentValue)){
					$errorMessages[] = "Current value of goal is invalid."; 
				}
				if (!is_integer2($targetValue)){
					$errorMessages[] = "Target value of goal is invalid."; 
				}
				if(count($errorMessages) == 0){
					if(!(intval($startValue) <= intval($currentValue) && intval($currentValue) <= intval($targetValue))){
						$errorMessages[] = "Current value of goal is not between start and target values."; 
					}
				}
				break;
			case '2': # float				
				# replace first comma with decimal point			
				$startValue = str_replace( ",", ".", $startValue);
				$currentValue = str_replace( ",", ".", $currentValue);
				$targetValue = str_replace( ",", ".", $targetValue);
				$_POST['startvalue'] = $startValue;
				$_POST['$currentValue'] = $currentValue;
				$_POST['$targetValue'] = $targetValue;
				
				if (!is_float2($startValue)){
					$errorMessages[] = "Start value of goal is invalid."; 
				}
				if (!is_float2($currentValue)){
					$errorMessages[] = "Current value of goal is invalid."; 
				}
				if (!is_float2($targetValue)){
					$errorMessages[] = "Target value of goal is invalid."; 
				}
				if(count($errorMessages) == 0){
					if(!(floatval($startValue) <= floatval($currentValue) && floatval($currentValue) <= floatval($targetValue))){
						$errorMessages[] = "Current value of goal is not between start and target values."; 
					}
				}
				break;
			case '3': # money
				# replace first comma with decimal point			
				$startValue = str_replace( ",", ".", $startValue);
				$currentValue = str_replace( ",", ".", $currentValue);
				$targetValue = str_replace( ",", ".", $targetValue);
				$_POST['startvalue'] = $startValue;
				$_POST['$currentValue'] = $currentValue;
				$_POST['$targetValue'] = $targetValue;
				
				if (!is_float2($startValue) || !hasTwoDigitsAfterDecimalPoint($startValue)){
					$errorMessages[] = "Start value of goal is invalid.";
				}
				if (!is_float2($currentValue) || !hasTwoDigitsAfterDecimalPoint($currentValue)){
					$errorMessages[] = "Current value of goal is invalid."; 
				}
				if (!is_float2($targetValue) || !hasTwoDigitsAfterDecimalPoint($targetValue)){
					$errorMessages[] = "Target value of goal is invalid."; 
				}
				if(count($errorMessages) == 0){
					if(!(floatval($startValue) <= floatval($currentValue) && floatval($currentValue) <= floatval($targetValue))){
						$errorMessages[] = "Current value of goal is not between start and target values."; 
					}
				}
				break;
			case '4': #yes/no
				if ($startValue != "no"){
					$errorMessages[] = "Start value for measure type \"yes/no\" should be \"no\"";
				}
				if (!($currentValue == "no" || $currentValue == "yes" )){
					$errorMessages[] = "Current value for measure type \"yes/no\" should be \"yes\" or \"no\"";
				}
				if ($targetValue != "yes"){
					$errorMessages[] = "Target value for measure type \"yes/no\" should be \"yes\"";
				}
				
				break;
			case '5': #percent
				if ($startValue != "0"){
					$errorMessages[] = "Start value of goal is invalid. Correct value is 0."; 
				}
				if (!is_integer2($currentValue)){
					$errorMessages[] = "Current value of goal should be an integer."; 
				}
				if ($targetValue != 100){
					$errorMessages[] = "Target value of goal is invalid. Correct value is 100."; 
				}
				if(count($errorMessages) == 0){
					if(!(intval($startValue) <= intval($currentValue) && intval($currentValue) <= intval($targetValue))){
						$errorMessages[] = "Current value of goal is not between 0 and 100 percent."; 
					}
				}
				break;
			
		}
		return $errorMessages;
	}
		
	function startsWith($haystack, $needle){
   	$length = strlen($needle);
    	return (substr($haystack, 0, $length) === $needle);
	}
	
	function is_integer2($value) {
		$intValue = intval($value);
		if ("$intValue" == "$value") {
			return true;
		} else {
			return false;
		}
	}
	
	function is_float2($value) {		
		$intValue = floatval($value);
		if ("$intValue" == "$value") {
			return true;
		} else {
			return false;
		}
	}
	
	function hasTwoDigitsAfterDecimalPoint($value){
		$temp = $value;
		if ($temp != str_replace(".","",$temp)){			
			return preg_match("/^[0-9]+(.[0-9]{2})?$/", $value);
		}
		return true;
	}
	
	function validateSubgoalsValues(){
		$errorMessages = array();
		foreach($_POST as $key=>$value) {
			if (startsWith($key, 'subgoalstartvalue')){
				$splittedKey = preg_split("/[_]/", $key);
				$subgoalId = $splittedKey[1];
				$startValue = $value;
				$currentValue = $_POST['subgoalcurrentvalue_'.$subgoalId];
				$targetValue = $_POST['subgoaltargetvalue_'.$subgoalId];
				$measureType = $_POST['subgoalmeasuretype_'.$subgoalId];
						
				$errorListSubGoalMeasureValues = array();
				$errorListSubGoalMeasureValues = validateGoalValues($measureType, $startValue, $currentValue, $targetValue);
				
				if(count($errorListSubGoalMeasureValues) > 0){
					$errorMessages[] = "Subgoal #".intval($subgoalId+1).":";
					$errorMessages = array_merge($errorMessages, $errorListSubGoalMeasureValues);
				}
			}
		}
		return $errorMessages;
	}
	
		function validateSubgoalsValuesOnEditPage(){
			$errorMessages = array();
			foreach($_POST as $key=>$value) {
				if (startsWith($key, 'subgoalstart_')){
					$splittedKey = preg_split("/[_]/", $key);
					$subgoalId = $splittedKey[1];
					$startValue = $value;
					$currentValue = $_POST['subgoalcurrent_'.$subgoalId];
					$targetValue = $_POST['subgoaltarget_'.$subgoalId];
					$measureType = $_POST['subgoalmeasuretype_'.$subgoalId];
					$subgoalname = $_POST['subgoalname_'.$subgoalId];
					if($subgoalname == ""){
						$subgoalname = "no name";
					}		
					$errorListSubGoalMeasureValues = array();
					$errorListSubGoalMeasureValues = validateGoalValues($measureType, $startValue, $currentValue, $targetValue);
					
					if(count($errorListSubGoalMeasureValues) > 0){
						$errorMessages[] = "Subgoal '".$subgoalname."':";
						$errorMessages = array_merge($errorMessages, $errorListSubGoalMeasureValues);
					}
				}
			}
			return $errorMessages;
		}

?>